import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Tree, 
  message, 
  Popconfirm,
  Row,
  Col,
  Descriptions
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  SearchOutlined,
  ReloadOutlined,
  TeamOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';

const { Search } = Input;
const { TextArea } = Input;

// 角色数据接口
interface RoleData {
  id: string;
  roleName: string;
  roleCode: string;
  description?: string;
  permissions: string[];
  createTime: string;
  updateTime: string;
  updateByUserName: string;
}

// 权限菜单数据
const permissionMenus: DataNode[] = [
  {
    title: '系统管理',
    key: 'system',
    children: [
      {
        title: '用户管理',
        key: 'user',
        children: [
          { title: '查看用户', key: 'user:view' },
          { title: '新增用户', key: 'user:add' },
          { title: '编辑用户', key: 'user:edit' },
          { title: '删除用户', key: 'user:delete' },
          { title: '重置密码', key: 'user:reset' },
        ]
      },
      {
        title: '角色管理',
        key: 'role',
        children: [
          { title: '查看角色', key: 'role:view' },
          { title: '新增角色', key: 'role:add' },
          { title: '编辑角色', key: 'role:edit' },
          { title: '删除角色', key: 'role:delete' },
        ]
      },
      {
        title: '菜单管理',
        key: 'menu',
        children: [
          { title: '查看菜单', key: 'menu:view' },
          { title: '新增菜单', key: 'menu:add' },
          { title: '编辑菜单', key: 'menu:edit' },
          { title: '删除菜单', key: 'menu:delete' },
        ]
      }
    ]
  },
  {
    title: '设备管理',
    key: 'equipment',
    children: [
      {
        title: '设备列表',
        key: 'equipment-list',
        children: [
          { title: '查看设备', key: 'equipment:view' },
          { title: '新增设备', key: 'equipment:add' },
          { title: '编辑设备', key: 'equipment:edit' },
          { title: '删除设备', key: 'equipment:delete' },
          { title: '设备控制', key: 'equipment:control' },
        ]
      },
      {
        title: '设备监控',
        key: 'equipment-monitor',
        children: [
          { title: '实时监控', key: 'monitor:realtime' },
          { title: '历史数据', key: 'monitor:history' },
          { title: '报警管理', key: 'monitor:alarm' },
        ]
      }
    ]
  },
  {
    title: '子系统管理',
    key: 'subsystem',
    children: [
      { title: '电梯系统', key: 'subsystem:elevator' },
      { title: '暖通空调', key: 'subsystem:hvac' },
      { title: '停车系统', key: 'subsystem:parking' },
      { title: '消防系统', key: 'subsystem:fire' },
      { title: '视频监控', key: 'subsystem:video' },
      { title: '门禁系统', key: 'subsystem:access' },
    ]
  },
  {
    title: '数据统计',
    key: 'statistics',
    children: [
      { title: '运营概览', key: 'statistics:overview' },
      { title: '设备统计', key: 'statistics:equipment' },
      { title: '报表中心', key: 'statistics:report' },
    ]
  }
];

// 模拟角色数据
const mockRoleData: RoleData[] = [
  {
    id: '1',
    roleName: '系统管理员',
    roleCode: 'ADMIN',
    description: '拥有系统所有权限的超级管理员',
    permissions: ['system', 'user', 'user:view', 'user:add', 'user:edit', 'user:delete', 'user:reset', 'role', 'role:view', 'role:add', 'role:edit', 'role:delete', 'menu', 'menu:view', 'menu:add', 'menu:edit', 'menu:delete', 'equipment', 'equipment-list', 'equipment:view', 'equipment:add', 'equipment:edit', 'equipment:delete', 'equipment:control', 'equipment-monitor', 'monitor:realtime', 'monitor:history', 'monitor:alarm', 'subsystem', 'subsystem:elevator', 'subsystem:hvac', 'subsystem:parking', 'subsystem:fire', 'subsystem:video', 'subsystem:access', 'statistics', 'statistics:overview', 'statistics:equipment', 'statistics:report'],
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-20 14:30:25',
    updateByUserName: '系统管理员'
  },
  {
    id: '2',
    roleName: '运维人员',
    roleCode: 'OPERATOR',
    description: '负责设备运维和监控的操作人员',
    permissions: ['equipment', 'equipment-list', 'equipment:view', 'equipment:edit', 'equipment:control', 'equipment-monitor', 'monitor:realtime', 'monitor:history', 'monitor:alarm', 'subsystem', 'subsystem:elevator', 'subsystem:hvac', 'subsystem:parking', 'statistics', 'statistics:overview', 'statistics:equipment'],
    createTime: '2024-01-16 09:15:00',
    updateTime: '2024-01-19 16:20:10',
    updateByUserName: '系统管理员'
  },
  {
    id: '3',
    roleName: '普通用户',
    roleCode: 'USER',
    description: '只能查看基本信息的普通用户',
    permissions: ['equipment', 'equipment-list', 'equipment:view', 'equipment-monitor', 'monitor:realtime', 'subsystem', 'subsystem:elevator', 'subsystem:hvac', 'subsystem:parking', 'statistics', 'statistics:overview'],
    createTime: '2024-01-17 14:45:00',
    updateTime: '2024-01-18 11:30:45',
    updateByUserName: '系统管理员'
  },
  {
    id: '4',
    roleName: '访客',
    roleCode: 'GUEST',
    description: '临时访问权限，只能查看基础信息',
    permissions: ['statistics', 'statistics:overview'],
    createTime: '2024-01-18 16:20:00',
    updateTime: '2024-01-20 09:15:30',
    updateByUserName: '系统管理员'
  }
];

const RoleList: React.FC = () => {
  const [roleData, setRoleData] = useState<RoleData[]>(mockRoleData);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  
  // 模态框状态
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<RoleData | null>(null);
  const [viewingRole, setViewingRole] = useState<RoleData | null>(null);
  
  // 表单实例
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();

  // 过滤数据
  const filteredData = roleData.filter(role => {
    return !searchText || 
      role.roleName.toLowerCase().includes(searchText.toLowerCase()) ||
      role.roleCode.toLowerCase().includes(searchText.toLowerCase());
  });

  // 表格列配置
  const columns: ColumnsType<RoleData> = [
    {
      title: '序号',
      key: 'index',
      width: 80,
      render: (_, __, index) => index + 1,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      width: 150,
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      width: 120,
      render: (code) => <Tag color="blue">{code}</Tag>,
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
      render: (description) => description || '--',
    },
    {
      title: '权限数量',
      dataIndex: 'permissions',
      key: 'permissions',
      width: 100,
      render: (permissions: string[]) => (
        <Tag color="green">{permissions.length} 项</Tag>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 160,
    },
    {
      title: '编辑人员',
      dataIndex: 'updateByUserName',
      key: 'updateByUserName',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除该角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理刷新
  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('数据刷新成功');
    }, 1000);
  };

  // 处理添加角色
  const handleAdd = () => {
    setIsAddModalVisible(true);
  };

  // 处理查看角色
  const handleView = (role: RoleData) => {
    setViewingRole(role);
    setIsDetailModalVisible(true);
  };

  // 处理编辑角色
  const handleEdit = (role: RoleData) => {
    setEditingRole(role);
    editForm.setFieldsValue({
      roleName: role.roleName,
      roleCode: role.roleCode,
      description: role.description,
      permissions: role.permissions
    });
    setIsEditModalVisible(true);
  };

  // 处理删除角色
  const handleDelete = (roleId: string) => {
    setRoleData(prev => prev.filter(role => role.id !== roleId));
    message.success('角色删除成功');
  };

  // 提交添加角色表单
  const handleAddSubmit = (values: any) => {
    const newRole: RoleData = {
      id: Date.now().toString(),
      roleName: values.roleName,
      roleCode: values.roleCode,
      description: values.description,
      permissions: values.permissions || [],
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString(),
      updateByUserName: '当前用户'
    };
    
    setRoleData(prev => [...prev, newRole]);
    setIsAddModalVisible(false);
    addForm.resetFields();
    message.success('角色添加成功');
  };

  // 提交编辑角色表单
  const handleEditSubmit = (values: any) => {
    if (!editingRole) return;
    
    const updatedRole: RoleData = {
      ...editingRole,
      roleName: values.roleName,
      roleCode: values.roleCode,
      description: values.description,
      permissions: values.permissions || [],
      updateTime: new Date().toLocaleString(),
      updateByUserName: '当前用户'
    };
    
    setRoleData(prev => prev.map(role => 
      role.id === editingRole.id ? updatedRole : role
    ));
    setIsEditModalVisible(false);
    setEditingRole(null);
    editForm.resetFields();
    message.success('角色更新成功');
  };

  // 获取权限名称
  const getPermissionNames = (permissions: string[]) => {
    const names: string[] = [];
    
    const findNames = (nodes: DataNode[], perms: string[]) => {
      nodes.forEach(node => {
        if (perms.includes(node.key as string)) {
          names.push(node.title as string);
        }
        if (node.children) {
          findNames(node.children, perms);
        }
      });
    };
    
    findNames(permissionMenus, permissions);
    return names;
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 26 }}>
          <Col span={8}>
            <Search
            size="large"
              placeholder="搜索角色名称或编码"
              allowClear
              onSearch={handleSearch}
              style={{ width: '100%', }}
            />
          </Col>
          <Col span={16} style={{ textAlign: 'right' }}>
            <Space>
              <Button 
              size="large"
                icon={<ReloadOutlined />} 
                onClick={handleRefresh}
              >
                刷新
              </Button>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                新增角色
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1000 }}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 添加角色模态框 */}
      <Modal
        title="新增角色"
        open={isAddModalVisible}
        onCancel={() => {
          setIsAddModalVisible(false);
          addForm.resetFields();
        }}
        footer={null}
        width={800}
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="roleName"
                label="角色名称"
                rules={[{ required: true, message: '请输入角色名称' }]}
              >
                <Input placeholder="请输入角色名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="roleCode"
                label="角色编码"
                rules={[{ required: true, message: '请输入角色编码' }]}
              >
                <Input placeholder="请输入角色编码" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="description"
            label="角色描述"
          >
            <TextArea rows={3} placeholder="请输入角色描述" />
          </Form.Item>
          <Form.Item
            name="permissions"
            label="权限配置"
          >
            <Tree
              checkable
              treeData={permissionMenus}
              style={{ border: '1px solid #d9d9d9', borderRadius: 6, padding: 8, maxHeight: 300, overflow: 'auto' }}
            />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => {
                setIsAddModalVisible(false);
                addForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑角色模态框 */}
      <Modal
        title="编辑角色"
        open={isEditModalVisible}
        onCancel={() => {
          setIsEditModalVisible(false);
          setEditingRole(null);
          editForm.resetFields();
        }}
        footer={null}
        width={800}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="roleName"
                label="角色名称"
                rules={[{ required: true, message: '请输入角色名称' }]}
              >
                <Input placeholder="请输入角色名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="roleCode"
                label="角色编码"
                rules={[{ required: true, message: '请输入角色编码' }]}
              >
                <Input placeholder="请输入角色编码" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="description"
            label="角色描述"
          >
            <TextArea rows={3} placeholder="请输入角色描述" />
          </Form.Item>
          <Form.Item
            name="permissions"
            label="权限配置"
          >
            <Tree
              checkable
              treeData={permissionMenus}
              style={{ border: '1px solid #d9d9d9', borderRadius: 6, padding: 8, maxHeight: 300, overflow: 'auto' }}
            />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => {
                setIsEditModalVisible(false);
                setEditingRole(null);
                editForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看角色详情模态框 */}
      <Modal
        title="角色详情"
        open={isDetailModalVisible}
        onCancel={() => {
          setIsDetailModalVisible(false);
          setViewingRole(null);
        }}
        footer={[
          <Button key="close" onClick={() => {
            setIsDetailModalVisible(false);
            setViewingRole(null);
          }}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {viewingRole && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="角色名称">{viewingRole.roleName}</Descriptions.Item>
              <Descriptions.Item label="角色编码">
                <Tag color="blue">{viewingRole.roleCode}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="角色描述">
                {viewingRole.description || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{viewingRole.createTime}</Descriptions.Item>
              <Descriptions.Item label="更新时间">{viewingRole.updateTime}</Descriptions.Item>
              <Descriptions.Item label="编辑人员">{viewingRole.updateByUserName}</Descriptions.Item>
            </Descriptions>
            
            <div style={{ marginTop: 16 }}>
              <h4>权限列表：</h4>
              <div style={{ maxHeight: 200, overflow: 'auto', border: '1px solid #d9d9d9', borderRadius: 6, padding: 8 }}>
                {getPermissionNames(viewingRole.permissions).map((name, index) => (
                  <Tag key={index} style={{ margin: '2px' }}>{name}</Tag>
                ))}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default RoleList;